<!--  -->
<template>
  <div class="model-open">
    <p class="header"><span @click="goprivatedetailedFun" class="header-btn">{{this.nameText}}</span><span class="header-text">&nbsp;>&nbsp;公开发布</span></p>
    <div class="con">
      <el-form
        label-position="left"
        class="form"
        :model="datasetForm"
        :rules="rulesForm"
        ref="datasetForm"
        @submit.native.prevent>
        <el-form-item lable-width="0px" prop="img">
          <div class="con-item con-item-center">
            <div class="left">
              模型封面
            </div>
            <div class="right">
              <!-- <div class="title">封面图片：</div> -->
              <el-upload
                ref="picUploader"
                class="upload"
                :drag="true"
                :limit="1"
                action="/gateway/fileCenter/api/file/qiniu/upload"
                :headers="uploadHeader"
                :on-change="handleImgChange"
                :on-exceed="handleExceed"
                :before-upload="handleBeforeUpload"
                accept="image/*">
                <div class="pic-uploader">
                  <img src="@/common/image/icon/icon-dataset-upload.png">
                  <div class="pic-uploader-text">
                    <p class="title">上传图片</p>
                    <p class="text">支持JPEG，JPG，PNG，大小不超过3M</p>
                  </div>
                </div>
              </el-upload>
            </div>
          </div>
        </el-form-item>
        <el-form-item lable-width="0px" prop="tag">
          <div class="con-item dataset-tag">
            <div class="left">
              标签
            </div>
            <div class="right tag-right">
              <div class="title">
                <span class="model-open-navs-detail-selected" v-for="item in selectedCategory" :key="item.id">{{item.name}}<i class="el-icon-close" @click="removeSelectedCategory(item.id)"></i></span>
                <el-popover
                  placement="bottom-start"
                  trigger="manual"
                  v-model="labelVisible"
                  width="800">
                  <div class="model-open-create-popover">
                    <ul class="navs-detail-left">
                      <li class="item" :class="{ 'active': openAllLabelIndex == index}" v-for="(item, index) in openAllLabel" :key="index" @click="showSeLabel(index)">{{item.name}}</li>
                    </ul>
                    <ul class="navs-detail-right">
                      <li class="items" v-for="(item, index) in openAllLabelShow" :key="index">
                        <h4 class="tit">{{item.name}}</h4>
                        <ul class="detail-items">
                          <li class="detail-item" v-for="(list, num) in item.childList" :key="num" @click="selectFilterLabel(list)">{{list.name}}</li>
                        </ul>
                      </li>
                    </ul>
                  </div>
                  <div class="model-open-navs-detail" slot="reference" @click="clickAddCategory">
                    <a class="model-open-navs-detail-more">+ 添加</a>
                  </div>
                </el-popover>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item class="open-item" lable-width="0px" prop="teamAddEmail">
          <div class="con-item con-item-centers">
            <div class="left">
              公开类型
            </div>
            <div class="right">
              <ul class="form-radio">
                <li class="radio-item radio-itema" :class="[{'active-category': curSelectedMyModel === 0},{'active-left': curSelectedMyModel === 0}]" @click="selectModelType(0)">公开给所有用户</li>
                <li class="radio-item radio-items" :class="{'active-category': curSelectedMyModel === 1}" @click="selectModelType(1)">公开给个人</li>
              </ul>
            </div>
          </div>
          <div class="con-sele">
            <div v-if="curSelectedMyModel === 0" class="openall">
              <p class="opentext">提示：该模型将对所有用户可见，且无法修改</p>
            </div>
            <div v-if="curSelectedMyModel === 1">
              <p class="opentext">提示：该模型将对你指定的用户可见，您也可以在这里取消公开</p>
              <div class="information-email">
                <div class="information-email-msg" :class="{'information-email-msg-btn': isEmailBorderBtn}">
                  <el-input
                    placeholder="输入邮箱号进行邀请"
                    v-model="datasetForm.teamAddEmail"
                    @keyup.enter.native="addPersonnelFun"
                    autocomplete="off"
                    clearable>
                  </el-input>
                </div>
                <div class="information-email-btn" @click="addPersonnelFun">搜索</div>
              </div>
              <ul class="information-email-back" v-if="accordingEnd">
                <li class="back-item">
                  <div class="back-item-portrait">
                    <img :src="objEmail.headImage ? objEmail.headImage : dattSetImgUrl" alt="">
                  </div>
                  <p class="back-item-con">
                    <span>{{objEmail.username}}</span>{{objEmail.email}}
                  </p>
                  <div class="back-item-add" @click="addMembersIDfun" @mouseover="addmebershow=true" @mouseleave="addmebershow=false">
                    <img v-if="addmebershow" src="@/common/image/team-add-people-active.png" alt="">
                    <img v-else src="@/common/image/team-add-people.png" alt="">
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </el-form-item >
        <div class="team-personnel-list" v-if="curSelectedMyModel === 1">
          <ul class="personnel-list-wrap" v-if="openPersonalRelations.length>0">
            <li
              class="personnel-item"
              v-for="(item, index) in openPersonalRelations"
              :key="index">
              <div class="personnel-item-ico">
                <img :src="item.headImage ? item.headImage : dattSetImgUrl" alt="">
              </div>
              <div class="personnel-item-text">
                <p class="item-text-name">{{item.username}}</p>
                <p class="item-text-email">{{item.email}}</p>
              </div>
              <div class="personnel-item-dele">
                <img v-if="item.addUser" src="@/common/image/delete-members.png" @click="delePersonnelFun(index)" alt="">
                <p v-else @click="deletePersonalRelationFun(item.id,item.username)">取消公开</p>
              </div>
            </li>
          </ul>
        </div>
        <el-form-item class="submitbtn">
          <el-button type="primary" @click="submitModelItemForm('datasetForm')">确定</el-button>
          <el-button type="primary" class="cancelbtn" @click="cancelModelItemForm('datasetForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="project-mask" v-show="labelVisible" @click="labelVisible=!labelVisible"></div>
  </div>
</template>

<script>
import { getCategoryTreeByType } from '@/api/category'
import { openModel, getPersonalRelation, deletePersonalRelation, getOpenCategory } from '@/api/model'
import { getSharingUserInfo } from '@/api/dataset'
import qs from 'qs'
import store from '@/store.js'
import dataSetImg from '@/common/image/dataset.jpg'
export default {
  data () {
    const validateTag = (rule, value, callback) => {
      if (this.selectedCategory.length < 1) {
        callback(new Error('请选择模型所属标签'))
      } else {
        callback()
      }
    }
    const validateImg = (rule, value, callback) => {
      const uploadedImg = this.$refs.picUploader.uploadFiles
      if (uploadedImg.length < 1) {
        callback(new Error('请上传封面图片'))
      } else {
        callback()
      }
    }
    // 邮箱验证
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      this.isEmailBorderBtn = false
      setTimeout(() => {
        if (mailReg.test(value)) {
          this.inputTeamAddEmail = true
          callback()
        } else if (value === '') {
          this.isEmailBorderBtn = true
          this.inputTeamAddEmail = false
          callback()
        } else {
          this.inputTeamAddEmail = false
          callback(new Error('邮箱格式不正确'))
        }
      }, 100)
    }
    return {
      inputTeamAddEmail: false,
      // 标签集合显示
      labelVisible: false,
      // 标签树分类 index
      openAllLabelIndex: 0,
      // 标签分类树信息
      openAllLabel: [],
      // 标签树分类显示
      openAllLabelShow: [],
      // 已选标签
      selectedCategory: [],
      // 搜索避免重复点击
      addRepeatBtn: true,
      isEmailBorderBtn: false,
      // 默认图片
      dattSetImgUrl: dataSetImg,
      accordingEnd: false,
      addmebershow: false,
      objEmail: {},
      teamPersonnelList: [],
      openPersonalRelation: [],
      openPersonalRelations: [],
      datasetForm: {
        teamAddEmail: ''
      },
      rulesForm: {
        img: [
          { validator: validateImg }
        ],
        tag: [
          { validator: validateTag }
        ],
        teamAddEmail: [
          { required: false, validator: checkEmail, trigger: 'blur' }
        ]
      },
      nameText: '',
      curSelectedMyModel: 0,
      // 搜索邮箱
      searchEmailBtn: true
    }
  },

  // components: {},

  computed: {
    // 图片上传header
    uploadHeader: () => {
      let obj = {
        token: store.state.userInfo.token,
        bitaToken: store.state.userInfo.bitaToken,
        userId: store.state.userInfo.userId
      }
      return obj
    }
  },

  mounted () {
    this._getCategoryTreeByType()
    this._getPersonalRelation()
    this.nameText = this.$route.query.modelNameText
    if (this.$route.query.modelOpenPersonal) {
      this._getOpenCategory()
      this.curSelectedMyModel = 1
    }
  },

  methods: {
    // 显示二级标签内容
    showSeLabel (index) {
      this.openAllLabelIndex = index
      this.openAllLabelShow = this.openAllLabel[index].childList
    },
    selectModelType (type) {
      this.curSelectedMyModel = type
    },
    // 选中过滤标签
    selectFilterLabel (item) {
      this.labelVisible = false
      const checkExist = this.selectedCategory.find(el => {
        return item.id === el.id
      })
      if (checkExist === undefined) {
        this.selectedCategory.push(item)
      }
      this.$refs['datasetForm'].validateField('tag', (validMessage) => {
        if (validMessage !== '') {
          return false
        } else {
          return true
        }
      })
    },
    addMembersIDfun () {
      this.teamPersonnelList.push(this.objEmail)
      this.openPersonalRelations = this.teamPersonnelList.concat(this.openPersonalRelation)
      this.datasetForm.teamAddEmail = ''
      this.accordingEnd = false
    },
    // 回到详情页
    goprivatedetailedFun () {
      this.$router.push({ path: '/modellump/privatedetailed', query: { active: 1, modelId: this.$route.query.modelId } })
    },
    // 搜索邮箱对应账户
    addPersonnelFun () {
      if (this.searchEmailBtn) {
        this.searchEmailBtn = false
        this.$refs['datasetForm'].validateField('teamAddEmail', (validMessage) => {
          if (validMessage !== '') {
            this.searchEmailBtn = true
            this.accordingEnd = false
            return false
          } else {
            if (this.inputTeamAddEmail) {
              for (var i = 0; i < this.openPersonalRelations.length; i++) {
                if (this.openPersonalRelations[i].email === this.datasetForm.teamAddEmail) {
                  this.$message({ message: '该成员已在队列里', showClose: true, type: 'error' })
                  this.searchEmailBtn = true
                  return false
                }
              }
              this._getSharingUserInfo()
            } else {
              this.searchEmailBtn = true
            }
          }
        })
      } else {
        return false
      }
      // this.$refs['datasetForm'].validate()
      // if (this.addRepeatBtn) {
      //   if (this.userInfo.email === this.teamInformationForm.teamAddEmail) {
      //     this.$message({ message: '您不能添加自己为成员', showClose: true, type: 'error' })
      //     return false
      //   } else {
      //     this.addRepeatBtn = false
      //     this._getUserInfoByEmail()
      //   }
      // }
    },
    // 添加标签
    clickAddCategory () {
      if (this.selectedCategory.length === 3) {
        this.$message({ message: '最多添加3个标签', showClose: true, type: 'warning' })
        return false
      } else {
        this.labelVisible = !this.labelVisible
      }
    },
    handleExceed () {
      this.$message({ message: '请选择一张封面图片上传', showClose: true, type: 'error' })
    },
    handleImgChange () {
      this.$refs['datasetForm'].validate()
    },
    // 上传图片类型大小判断
    handleBeforeUpload (file) {
      const isImage = file.type.indexOf('image/') > -1
      const isLt3M = file.size / 1024 / 1024 < 3
      if (!isImage) {
        this.$message.error('请选择图片上传')
      }
      if (!isLt3M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }
      return isImage && isLt3M
    },
    submitModelItemForm (agm) {
      console.log('33')
      if (this.openPersonalRelations.length === 0 && this.curSelectedMyModel === 1) {
        this.$router.push({ path: '/modellump/privatedetailed', query: { active: 1, modelId: this.$route.query.modelId, modelName: this.$route.query.modelNameText } })
      } else if (this.$route.query.modelOpenPersonal === true) {
        console.log(this.$route.query.modelOpenPersonal)
        this.$refs['datasetForm'].validateField('tag', (validMessage) => {
          if (validMessage !== '') {
            return false
          } else {
            this._uploadModelSet()
          }
        })
      } else {
        this.$refs[agm].validate((valid) => {
          if (valid) {
            this.isEmailBorderBtn = true
            this._uploadModelSet()
          } else {
            this.isEmailBorderBtn = true
            return false
          }
        })
      }
    },
    cancelModelItemForm (agm) {
      this.$refs[agm].resetFields()
      this.$router.push({ path: '/modellump/privatedetailed', query: { active: 1, modelId: this.$route.query.modelId, modelName: this.$route.query.modelNameText } })
    },
    // 移除选中标签
    removeSelectedCategory (id) {
      const removeIndex = this.selectedCategory.findIndex(el => {
        return el.id === id
      })
      this.selectedCategory.splice(removeIndex, 1)
    },
    // 获取分类树信息
    _getCategoryTreeByType () {
      const type = 1
      getCategoryTreeByType(type).then(res => {
        if (res.message.code === 0) {
          this.openAllLabel = res.data
          if (res.data.length > 0 && res.data[0].childList) this.openAllLabelShow = res.data[0].childList
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    },
    // 已发布过获取标签
    _getOpenCategory () {
      let query = ''
      query = `?modelId=${this.$route.query.modelId}`
      getOpenCategory(query).then(res => {
        if (res.message && res.message.code === 0) {
          this.selectedCategory = res.data
        } else {
          return false
        }
      })
    },
    // 搜索邮箱
    _getSharingUserInfo () {
      let query = ''
      query = `?email=${this.datasetForm.teamAddEmail}`
      getSharingUserInfo(query).then(res => {
        if (res.message && res.message.code === 0) {
          this.accordingEnd = true
          this.objEmail = {}
          this.objEmail.id = res.data.userId
          this.objEmail.headImage = res.data.headImage
          this.objEmail.username = res.data.username
          this.objEmail.email = this.datasetForm.teamAddEmail
          this.objEmail.addUser = true
        } else if (res.message.code === 20005) {
          this.$message({ message: '没有查找到该用户', showClose: true, type: 'error' })
          this.datasetForm.teamAddEmail = ''
        } else {
          this.$message({ message: '用户异常', showClose: true, type: 'error' })
          this.datasetForm.teamAddEmail = ''
        }
        this.searchEmailBtn = true
      })
    },
    // 删除成员
    delePersonnelFun (agm) {
      this.teamPersonnelList.splice(agm, 1)
      this.openPersonalRelations = this.teamPersonnelList.concat(this.openPersonalRelation)
    },
    // 查询公开用户
    _getPersonalRelation () {
      let query = ''
      query = `?modelId=${this.$route.query.modelId}`
      getPersonalRelation(query).then(res => {
        this.loadingMorePublic = false
        if (res.message.code === 0) {
          this.openPersonalRelation = res.data
          this.openPersonalRelations = this.openPersonalRelation
        } else {
          return false
        }
      })
    },
    // 删除公开用户
    deletePersonalRelationFun (agm, name) {
      let query = ''
      query = `?modelId=${this.$route.query.modelId}&userId=${agm}`
      deletePersonalRelation(query).then(res => {
        this.loadingMorePublic = false
        if (res.message && res.message.code === 0) {
          this.$message({ message: `已取消对${name}的公开！`, showClose: true, type: 'success' })
          this._getPersonalRelation()
        } else {
          return false
        }
      })
    },
    _uploadModelSet () {
      let uploadFiles = this.$refs.picUploader.uploadFiles
      let para = ''
      let part = false
      if (uploadFiles.length > 0) {
        let arr = uploadFiles.map(item => {
          return item.response.data.id
        })
        para = arr.toString()
      }
      let tagLists = []
      let userLists = []
      this.selectedCategory.map(item => {
        tagLists.push(item.id)
      })
      this.teamPersonnelList.map(item => {
        userLists.push(item.id)
      })
      if (this.curSelectedMyModel === 1) {
        part = false
      } else {
        part = true
      }
      let data = qs.stringify({
        tagList: tagLists,
        modelId: this.$route.query.modelId,
        modelCoverId: para,
        openAll: part,
        userList: userLists
      }, {
        indices: false
      })
      openModel(data).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '模型公开成功！', showClose: true, type: 'success' })
          this.$router.push({ path: '/modellump/privatedetailed', query: { active: 1, modelId: this.$route.query.modelId, modelName: this.$route.query.modelNameText } })
        } else if (res.message.code === 20011) {
          this.$message({ message: '不能公开给自己!', showClose: true, type: 'error' })
        } else {
          this.$message({ message: '模型公开失败,请重试!', showClose: true, type: 'error' })
        }
        this.basicEditorShow = false
      })
    }
  }
}

</script>
<style lang="stylus">
.model-open
  width 100%
  background #ffffff!important
  .header
    position relative
    margin 99px auto 34px
    max-width 1162px
    padding-left 311px
    box-sizing border-box
    font-size 18px
    line-height 20px
    font-weight 600
    color #2196F3
    .header-text
      color #001400
    .header-btn
      cursor pointer
  .con
    margin 0 auto 0
    max-width 1162px
    padding-left 311px
    box-sizing border-box
    .form
      .submitbtn
        padding-left 110px
        .el-button
          padding 10px 44px
          font-size 14px
          margin-right 18px
          line-height 20px
          border-radius 3px
          box-sizing border-box
        .cancelbtn
          background #ffffff
          border 1px solid #CCCCCC
          color #24292E
          &:hover
            background #F8F9FA
      .team-personnel-list
        width 543px
        padding-left 110px
        max-height 320px
        overflow-x hidden
        overflow-y auto
        margin-top 24px
        margin-bottom 59px
        .personnel-list-wrap
          height auto
          .personnel-item
            height 42px
            margin-bottom 24px
            overflow hidden
            display flex
            align-items center
            .personnel-item-ico
              width 32px
              height 32px
              border-radius 50% 50%
              overflow hidden
              margin-right 12px
              img
                width 32px
                height 32px
            .personnel-item-text
              width 326px
              .item-text-name
                team-item-style(1)
                font-size 14px
                line-height 20px
                color #2E94F9
              .item-text-email
                team-item-style(1)
                font-size 14px
                line-height 20px
                color #666666
                margin-top 2px
            .personnel-item-dele
              width 82px
              height 20px
              display flex
              cursor pointer
              justify-content left
              align-items center
              img
                width 11px
                height 11px
              p
                font-size 13px
                line-height 18px
                color #2E94F9
          .personnel-item:nth-last-of-type(1)
            margin-bottom 0
      .el-form-item__error
        left 110px
      .el-form-item
        margin-bottom 34px
      .open-item
        margin-bottom 20px
      .con-item
        display flex
        .left
          font-size 14px
          line-height 20px
          color #2D323B
          font-weight 600
          width 110px
        .right
          width 433px
          .el-upload-dragger
            width 433px
            height 120px
          .pic-uploader
            display flex
            height 100%
            background #F4F4F4
            padding 41px 0px 42px 83px
            >img
              width 17px
              height 15px
              margin-right 8px
            .pic-uploader-text
              text-align left
              .title
                font-size 14px
                color #2D323B
                line-height 20px
              .text
                font-size 12px
                color #2A2A2A
                line-height 20px
          .form-radio
            width 260px
            display flex
            border-radius 3px
            text-align center
            overflow hidden
            .radio-item
              padding 9px 13px
              font-size 14px
              line-height 20px
              color #2D323B
              transition all 0.2s linear
              cursor pointer
            .radio-itema
              border-radius 3px 0 0 3px
              border 1px solid #D1D2D3
              border-right 1px solid #D1D2D3
            .radio-items
              border-radius 0 3px 3px 0
              border 1px solid #D1D2D3
              border-left 0
            .active-category
              background #E6F1FC
              border-color #A3D0FD
              color #2E94F9
            .active-left
              border-right-color #D1D2D3
          .task
            .tasp-text
              font-size 12px
              line-height 20px
              color #808080
              padding 12px 0 24px
              span
                color #2E94F9
                padding-left 8px
        .tag-right
          width 733px
      .con-item-center
        align-items center
      .con-item-centers
        align-items center
      .con-sele
        padding-left 110px
        width 543px
        .opentext
          font-size 13px
          line-height 18px
          color #808080
          padding 16px 0 24px
        .information-email
          display flex
          justify-content space-between
          .information-email-msg
            width 337px
          .information-email-msg-btn
            .el-input__inner
              border-color #c0c4cc
          .information-email-btn
            width 88px
            height 40px
            line-height 40px
            text-align center
            font-size 14px
            color #ffffff
            background #2E94F9
            border-radius 4px
            cursor pointer
        .information-email-back
          position absolute
          bottom -62px
          left 110px
          .back-item
            display flex
            align-items center
            width 337px
            background #ffffff
            border 1px solid #cccccc
            border-radius 4px
            padding 25px 21px 13px 14px
            .back-item-portrait
              width 20px
              height 20px
              font-size 0
              margin-right 7px
              border-radius 50% 50%
              overflow hidden
              img
                width 100%
                height 100%
            .back-item-con
              width 250px
              font-size 12px
              color #666666
              line-height 17px
              word-break break-all
              word-wrap break-word
              overflow hidden
              text-overflow ellipsis
              display -webkit-box
              /*! autoprefixer: off */
              -webkit-box-orient vertical
              /* autoprefixer: on */
              -webkit-line-clamp 1
              span
                font-size 14px
                line-height 20px
                color $fontcolor
                margin-right 9px
            .back-item-add
              float right
              width 14px
              height 14px
              margin-top 2px
              font-size 0
              cursor pointer
              img
                display block
                width 100%
                height 100%
      .dataset-tag
        .model-open-navs-detail-selected
          background #F4F4F4
          border 1px solid #CCCCCC
          border-radius 4px
          font-size 14px
          color #2D323B
          font-weight normal
          padding 6px 14px
          margin-right 14px
          >i
            cursor pointer
            margin-left 5px
        .model-open-navs-detail
          position relative
          z-index 12
          display inline-block
          .model-open-navs-detail-more
            font-size 14px
            color #6E6E6E
            font-weight normal
            background #F4F4F4
            border 1px dashed #CCCCCC
            border-radius 4px
            padding 6px 14px
.model-open-create-popover
  width 100%
  display flex
  .navs-detail-left
    flex 0 0 120px
    padding-top 10px
    background #F4F7F8
    .item
      height 32px
      line-height 32px
      text-indent 10px
      font-size 16px
      font-weight 600
      cursor pointer
      &:hover
        color #2296f3
    .active
      color #2296f3
  .navs-detail-right
    flex 1
    padding-top 10px
    .items
      width 100%
      display flex
      .tit
        flex 0 0 140px
        height 32px
        line-height 32px
        text-align left
        padding 0 10px
        font-size 14px
        font-weight 600
      .detail-items
        flex 1
        font-size 0
        .detail-item
          display inline-block
          padding-left 6px
          padding-right 6px
          height 32px
          line-height 32px
          font-size 14px
          color #333
          cursor pointer
          &:hover
            color #2196f3
.project-mask
  position fixed
  top 68px
  right 0
  bottom 0
  left 0
  z-index 11
  background transparent
</style>
